<template>
  <basic-container page-title="用户列表" custom-content>
    <template #filter>
      <user-filter-bar
        v-model="filterBarState"
        :is-select="!!selectedRows?.length"
        :loading="false"
        @join-group="openJoinGroupDialog()"
        @create="openEditUserDialog()"
        @search="handleSearch()"
        @refresh="getList()"
      />
    </template>

    <el-table
      ref="tableRef"
      v-loading="loading"
      :data="tableList"
      class="basic-table"
      :tooltip-options="{ popperClass: 'basic-tooltip' }"
      height="100%"
      @sort-change="handleSortChange"
      @selection-change="handleTableSelectionChange"
    >
      <template #empty><TableEmpty /></template>
      <el-table-column type="selection" fixed="left" width="50" />
      <el-table-column label="用户ID" width="150">
        <template #default="{ row }">
          <el-link type="primary" :underline="false" @click="toUserDetail(row)">
            <span v-format-table-cell="row.uid"></span>
          </el-link>
        </template>
      </el-table-column>
      <el-table-column label="账号" min-width="160" show-overflow-tooltip>
        <template #default="{ row }">
          <span v-format-table-cell="row.username"></span>
        </template>
      </el-table-column>
      <el-table-column label="邮箱" show-overflow-tooltip min-width="150">
        <template #default="{ row }">
          <span v-format-table-cell="row.email"></span>
        </template>
      </el-table-column>
      <el-table-column label="域名数" show-overflow-tooltip min-width="120">
        <template #default="{ row }">
          <span v-format-table-cell="row.domain_num"></span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="DNS服务器地址" min-width="220">
        <template #default="{ row }">
          <div class="flex items-center justify-between">
            <div class="table-dns-wrapper">
              <div
                v-for="(item, index) in row.assign_ns_list"
                :key="index"
                class="dns"
              >
                <TextEll :offset="2" :content="emptyText(item?.addr)" />
              </div>
            </div>
            <el-icon
              class="cursor-pointer"
              color="#164CFF"
              size="16"
              @click="openEditDnsDialog(row)"
            >
              <Edit />
            </el-icon>
          </div>
        </template>
      </el-table-column> -->
      <el-table-column
        prop="group_name"
        label="分组"
        show-overflow-tooltip
        :formatter="emptyFormatter"
        min-width="150"
      />
      <el-table-column label="状态" width="100">
        <template #default="{ row }">
          <basic-switch
            :model-value="row.status"
            @click="handleEditStatus(row)"
          ></basic-switch>
        </template>
      </el-table-column>
      <el-table-column label="备注" min-width="220">
        <template #default="{ row }">
          <basic-edit-table-remark
            :content="row.remark"
            :submit="value => handleEditRemark(row, value)"
          ></basic-edit-table-remark>
        </template>
      </el-table-column>
      <!-- <el-table-column
        sortable="custom"
        prop="created_at"
        label="注册/创建时间"
        width="180"
      >
        <template #default="{ row }">
          <span v-format-unix="row.created_at"></span>
        </template>
      </el-table-column> -->
      <el-table-column
        sortable="custom"
        prop="updated_at"
        label="更新时间"
        width="180"
      >
        <template #default="{ row }">
          <span v-format-unix="row.updated_at"></span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="250">
        <template #default="{ row }">
          <div class="flex items-center gap-x-4">
            <el-link
              class="font-normal"
              type="primary"
              :underline="false"
              @click="toUserDetail(row)"
            >
              详情
            </el-link>
            <el-link
              class="font-normal"
              type="primary"
              :underline="false"
              @click="toUserDomainView(row)"
            >
              域名管理
            </el-link>
            <el-link
              class="font-normal"
              type="primary"
              :underline="false"
              @click="openEditUserDialog(row)"
            >
              编辑
            </el-link>
            <el-link
              class="font-normal"
              type="primary"
              :underline="false"
              @click="handleResetUserPassword(row)"
            >
              重置密码
            </el-link>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <template #footer>
      <basic-pagination
        ref="paginationRef"
        :table-ref="tableRef"
        :pagination="pagination"
        :batch-button-props="{
          disabled: !selectedRows || selectedRows.length === 0
        }"
        :batch-click="openJoinGroupDialog"
        @change="getList()"
      ></basic-pagination>
    </template>
  </basic-container>

  <join-group-dialog
    v-model:visible="joinGroup.visible"
    v-model:loading="joinGroup.loading"
    @reload="getList"
  ></join-group-dialog>

  <edit-dns-dialog
    v-model:visible="editDns.visible"
    v-model:loading="editDns.loading"
    :record="editDns.record"
    :save-method="handleEditDnsServer"
    @reload="getList"
  ></edit-dns-dialog>

  <edit-user-dialog
    v-model:visible="editUser.visible"
    v-model:loading="editUser.loading"
    :record="editUser.record"
    @reload="getList"
  ></edit-user-dialog>
  <ResetPasswordDialog
    v-model:visible="resetPasswordState.visible"
    :record="resetPasswordState.record"
    @reload="getList"
  />
</template>

<script setup lang="ts">
import type { TableInstance } from 'element-plus'

import type { UserModel } from '@/apis/model/user'
import { EditDnsDialog } from '@/components/business'
import { useFilterBarState } from '@/hooks/useFilterBarState'
import { useListRequest } from '@/hooks/useListRequest'
import useTableSelection from '@/hooks/useTableSelection'

import UserFilterBar from './components/UserFilterBar.vue'
import EditUserDialog from './dialogs/EditUserDialog.vue'
import JoinGroupDialog from './dialogs/JoinGroupDialog.vue'
import ResetPasswordDialog from './dialogs/ResetPasswordDialog.vue'
import useUserAction from './hooks/useUserAction'

const tableRef = ref<TableInstance>()
const paginationRef = ref()

const formState = reactive({
  sort: '',
  order: ''
})

const { filterBarState, queryState } = useFilterBarState(formState)

/**
 * 获取列表数据
 */
const {
  data: tableList,
  getList,
  pagination,
  loading
} = useListRequest(userListApi, queryState)

onMounted(getList)

const resetPasswordState = reactive<CommonDialog>({
  visible: false,
  record: undefined
})

const handleResetUserPassword = (row: UserModel) => {
  resetPasswordState.visible = true
  resetPasswordState.record = row
}

/**
 * 搜索
 */
const handleSearch = () => {
  pagination.page = 1
  getList()
}

function handleSortChange(params: SortParams) {
  const { sort, order } = getSortValue(params)
  formState.sort = sort!
  formState.order = order!
  pagination.page = 1
  getList()
}

/**
 * 选择的表格数据
 */
const { selectedRows, handleTableSelectionChange } = useTableSelection(
  tableList,
  paginationRef
)

/**
 * 加入组
 */
const joinGroup = reactive<CommonDialog>({
  visible: false,
  loading: false
})
const openJoinGroupDialog = () => {
  joinGroup.visible = true
}

/**
 * 修改dns服务器地址
 */
const editDns = reactive<CommonDialog<{ id: string; dns: [string, string] }>>({
  visible: false,
  loading: false,
  record: undefined
})

// const openEditDnsDialog = (user: UserModel) => {
//   if (user.assign_ns_list) {
//     editDns.record = {
//       id: user.id as string,
//       dns: [
//         user.assign_ns_list[0].id as string,
//         user.assign_ns_list[1].id as string
//       ]
//     }
//   }

//   editDns.visible = true
// }

/**
 * 编辑用户
 */
const editUser = reactive<CommonDialog<UserModel | null>>({
  visible: false,
  loading: false,
  record: null
})
const openEditUserDialog = (user?: UserModel) => {
  editUser.record = user
  editUser.visible = true
}

const {
  toUserDetail,
  toUserDomainView,
  handleEditStatus,
  handleEditDnsServer,
  handleEditRemark
} = useUserAction(getList)

provide('selectedRows', selectedRows)
</script>

<style scoped lang="scss"></style>
